package com.demo.salary.payrollimplementation;


import com.demo.salary.payrolldomain.Affiliation;
import com.demo.salary.PayCheck;
import com.demo.salary.Util;

import java.time.Period;
import java.util.ArrayList;
import java.time.LocalDate;
import java.util.List;

public class UnionAffiliation implements Affiliation {
    int memberId;
    double weeklyCharge;

    private static final int CHARGE_DAY_OF_WEEK = 5;
    List<ServiceCharge> serviceCharges = new ArrayList<>();

    public UnionAffiliation( int memberId,double dues) {
        this.weeklyCharge = dues;
        this.memberId = memberId;
    }

    public double getWeeklyCharge() {
        return weeklyCharge;
    }

    public int getMemberId() {
        return memberId;
    }

    public void addServiceCharge(ServiceCharge serviceCharge) {
        serviceCharges.add(serviceCharge);
    }
    public ServiceCharge getServiceCharge(LocalDate date){
        for (ServiceCharge serviceCharge : serviceCharges) {
            if (date.equals(serviceCharge.getDate())) {
                return serviceCharge;
            }
        }
        return null;
    }

    @Override
    public double calculateDeductions(PayCheck paycheck) {
        double deduce = numberOfChargeInPayPeriod(paycheck.getPayPeriodStartDate(), paycheck.getItsPayDate()) * weeklyCharge;
        for (ServiceCharge serviceCharge : serviceCharges) {
            if (Util.inPeriod(serviceCharge.getDate(), paycheck.getPayPeriodStartDate(), paycheck.getItsPayDate())) {
                deduce += serviceCharge.getAmount();
            }
        }
        return deduce;
    }
    private int numberOfChargeInPayPeriod(LocalDate start, LocalDate end) {
        int days = Period.between(start, end).getDays() + 1;
        int startDayOfWeek = start.getDayOfWeek().getValue();
        return Util.numberDayOfWeekInDays(CHARGE_DAY_OF_WEEK, startDayOfWeek, days);
    }
}
